import sys
import os
from urllib2 import HTTPError, URLError
from datetime import date
from calendar import Calendar

import ParseHelpUtils
import WebUtils
import EventInfo
import Cache
from EventInfoTemplate import EventInfoTemplate

#===================================================================

def get_coordinates(places, loc_cache, nohits_cache):
   
    coordinates = dict()
    updates = dict()
    nohits = dict()
    
    for place_name in places:
        if place_name != "":
            lat_long = loc_cache.get_item(place_name)
            
            if lat_long:
                coordinates[place_name] = lat_long
                continue
            
            if not nohits_cache.get_item(place_name):
                lat_long = WebUtils.lookup_google(place_name)
                
                if lat_long:
                    updates[place_name] = lat_long
                    coordinates[place_name] = lat_long 
                else:
                    nohits[place_name] = 'P' # Dummy "value"
                    places.remove(place_name)

    return coordinates, updates, nohits

#===================================================================
def transform_event_infos(event_infos):
	event_info_list = []

	for event_info in event_infos:
		for event_location, latlong in event_info.event_locations.iteritems():
			event_info_list.append(EventInfoTemplate(event_info.event.encode("utf-8"), 
														event_location.encode("utf-8"), 
														latlong['lat'],
														latlong['lng']))

	return event_info_list

#===================================================================

def events_of_the_day(day_of_year):

    wikipedia_base_url = "http://en.wikipedia.org/wiki/"
    
    wikipedia_url = "{0}{1}".format(wikipedia_base_url, day_of_year)

    if not day_of_year:
        day_of_year = date.today().strftime('%B_%d')
        
    event_infos = list()

    APP_ROOT = os.path.dirname(os.path.realpath(__file__))
    CACHE_PATH = os.path.join(APP_ROOT, '../cache')
    HITS_CACHE = os.path.join(CACHE_PATH, 'places.txt')
    NOHITS_CACHE = os.path.join(CACHE_PATH, 'nohits.txt')

    try:
        print "Loading Cache from", HITS_CACHE
        loc_cache = Cache.Cache(HITS_CACHE)
        loc_cache.load_cache()
    
        print "Loading No-Hits Cache from", NOHITS_CACHE
        nohits_cache = Cache.Cache(NOHITS_CACHE)
        nohits_cache.load_cache()
    
    except (IOError) as (strerror):
        print "Error loading Cache: {0}".format(strerror)
        return None
    
    try:        
        html_content = WebUtils.get_content(wikipedia_url)
    
    except (HTTPError) as error:
        print "Error fetching content from wikipedia: {0}".format(str(error))
        if error.code == 404:
            return error.code

        return None

    except (URLError) as error:
        print "Error fetching content from wikipedia: {0}".format(str(error))
        return None
    
    events = WebUtils.extract_events(html_content)

    coordinates = dict()
        
    for event in events:
        if event == "":
            continue
        
        places = ParseHelpUtils.guess_place_names(event)
        if places:
            coordinates, updates, nohits = get_coordinates(places, 
                                                           loc_cache, 
                                                           nohits_cache)

            event_info = EventInfo.EventInfo(event, coordinates)
                    
            if event_info.event_locations is not None:
                event_infos.append(event_info)

            if updates:
                if loc_cache.add_items(updates) == False:
                    print "Error adding items to cache"

            if nohits:
                if nohits_cache.add_items(nohits) == False:
                    print "Error adding items to nohits cache"
                
        else:
            print "No Places detected ==> %s", event.encode("utf-8")
    
    print "---------------------------------------------"
    
    try:
        if loc_cache.write_cache_to_disk() == False:
            print "Error updating Cache"
        
        if nohits_cache.write_cache_to_disk() == False:
            print "Error updating No-Hits Cache"
        
    except IOError as (errno, strerror):
        print "Error Updating Cache: errno: {0}, {1}".format(errno, strerror)
    
    return event_infos
#===================================================================

if __name__ == "__main__":
    
    if len(sys.argv) == 1:
        events_of_the_day(date.today().strftime('%B_%d'))
    else:
        events_of_the_day(sys.argv[1])
